const express = require('express');
const router = express.Router();
const qx = require("../../../utils/qx");
const { mysql } = require("../../../utils/require");
const { sendEmail } = require("../../../utils/mail")

router.get("/mail", (req, res) => {

    mysql.query("select hosts,port,auto_user,auto_pass,substring_index(mail_from,'<',1) as mail_from,mail_to,html,subject,icode from `mail` where username = ?", req.session.users.username, (err, doc) => {
        if (err) {
            return err
        }
        res.send(doc)
    })

})

router.post("/setmail", (req, res) => {

    let { hosts, port, auto_user, auto_pass } = req.body;

    mysql.query("select username from `mail`  where username= ? ", [req.session.users.username], (err, data) => {
        if (err) {
            return err
        }
        if (data.length == 0) {
            mysql.query("insert into `mail`  ( username,hosts,port,auto_user,auto_pass) values (?,?,?,?,?) ", [req.session.users.username, hosts, port, auto_user, auto_pass], (err, doc) => {
                if (err) {
                    return err
                }
                res.send({
                    code: 200,
                    messages: "保存成功"
                })
            })
        } else {
            mysql.query("update  `mail` set hosts = ?,port = ?,auto_user = ? ,auto_pass =? where  username = ?", [hosts, port, auto_user, auto_pass, req.session.users.username], (err, doc) => {
                if (err) {
                    return err
                }
                res.send({
                    code: 200,
                    messages: "保存成功"
                })
            })
        }

    })

})

router.post("/setmailoption", (req, res) => {
    let { mail_from, mail_to, html, icode } = req.body;
    let u = req.session.users.username;
    mysql.query("update `mail` set mail_from = ? ,mail_to= ?,html=?,icode= ? where username = ?", [mail_from, mail_to, html, icode, u], (err, doc) => {
        if (err) {
            throw err
        }
        res.send({ code: 200, messages: "保存成功" })

    })



})
router.post("/sendEmail", (req, res) => {
    let u = req.session.users.username;
    mysql.query("select * from `mail` where username = ?", u, async(err, doc) => {
        if (err) {
            throw err
        }
        let data = doc[0];
        let send = await sendEmail(data.hosts, data.port, data.auto_user, data.auto_pass, data.icode, data.mail_from, data.mail_to, data.html);
        res.send(send)
    })


})

module.exports = router